﻿using System;
using System.Collections.Generic;
using System.Text;
using FDSimpleModelGenerator.Common;
using FDSimpleModelGenerator.Json;
using Microsoft.Extensions.Options;
using StackExchange.Redis;

namespace FDSimpleModelGenerator.Cache.Redis
{
    /// <summary>
    /// Redis缓存
    /// </summary>
    public class RedisCache : ICache
    {
        private readonly RedisCacheConfig _redisCacheConfig;
        private readonly ConnectionMultiplexer _connection;
        private readonly IDatabase _database;

        public RedisCache(IOptions<RedisCacheConfig> redisCacheConfigOptions)
        {
            _redisCacheConfig = redisCacheConfigOptions.Value;
            _connection = ConnectionMultiplexer.Connect(_redisCacheConfig.ConnectionString);
            _database = _connection.GetDatabase(_redisCacheConfig.DatabaseIndex);
        }

        public T Get<T>(string key)
        {
            string result = _database.StringGet(key);
            if (typeof(T) == typeof(string))
            {
                return (T)Convert.ChangeType(result, typeof(T));
            }

            return result.FromJson<T>();
        }

        public T Get<T>(string key, Func<T> addIfNotExists, TimeSpan expires)
        {
            var result = Get<T>(key);
            if (result == null)
            {
                result = addIfNotExists();
                Set(key, result, expires);
            }

            return result;
        }

        public bool Set<T>(string key, T value, TimeSpan expires)
        {
            string result = typeof(T) == typeof(string) ? value.ToString() : value.ToJson();
            return _database.StringSet(key, result, expires);
        }
    }
}
